<template>
  <div class="materials">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-background">
        <el-carousel height="100%" indicator-position="outside" arrow="always" :autoplay="true" :interval="5000" :key="headerImagesKey">
          <el-carousel-item v-for="(img, idx) in headerImages" :key="idx">
            <img :src="img" alt="学习资料背景" class="header-bg-image" @click="handleHeaderImageClick(idx, img)" style="cursor: pointer;" />
          </el-carousel-item>
        </el-carousel>
        <div class="header-overlay"></div>
      </div>
      <div class="header-content">
        <h1>{{ $t('materials.title') }}</h1>
        <p>{{ $t('materials.subtitle') }}</p>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="filters-section">
      <div class="container">
        <div class="filters">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select v-model="selectedCategory" placeholder="选择分类" @change="filterMaterials">
                <el-option label="全部" value="all" />
                <el-option label="特定技能" value="tokutei" />
                <el-option label="JFT" value="jft" />
                <el-option label="JLPT" value="jlpt" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="selectedType" placeholder="选择类型" @change="filterMaterials">
                <el-option label="全部类型" value="all" />
                <el-option label="教材" value="textbook" />
                <el-option label="练习题" value="exercise" />
                <el-option label="模拟考试" value="mock" />
                <el-option label="指南" value="guide" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索资料..." 
                @input="filterMaterials"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="filterMaterials">
                {{ $t('common.search') }}
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 材料网格 -->
    <div class="materials-section">
      <div class="container">
        <div class="materials-grid">
          <div 
            v-for="material in filteredMaterials" 
            :key="material.id" 
            class="material-card"
          >
            <!--<div class="material-image">-->
              <!--<img :src="material.cover" :alt="material.title" />-->
              <!--<div class="material-overlay">-->
                <!--<el-button type="primary" @click="previewMaterial(material)">-->
                  <!--<el-icon><View /></el-icon>-->
                  <!--预览-->
                <!--</el-button>-->
              <!--</div>-->
            <!--</div>-->
            
            <div class="material-info">
              <h3>{{ material.title }}</h3>
              <p class="material-description">{{ material.description }}</p>
              
              <!--<div class="material-meta">-->
                <!--<div class="material-stats">-->
                  <!--<span class="downloads">{{ material.downloads }} 次下载</span>-->
                  <!--<span class="date">{{ material.uploadDate ? formatDate(material.uploadDate) : '' }}</span>-->
                <!--</div>-->
                
                <!--<div class="material-tags">-->
                  <!--<el-tag size="small" :type="getTagType(material.category)">-->
                    <!--{{ material.category }}-->
                  <!--</el-tag>-->
                  <!--<el-tag size="small" type="info">-->
                    <!--{{ material.type }}-->
                  <!--</el-tag>-->
                <!--</div>-->
              <!--</div>-->
              
              <div class="material-actions">
                <el-button type="primary" @click="downloadMaterialFun(material)">
                  <el-icon><Download /></el-icon>
                  {{ $t('materials.download') }}
                </el-button>
                <!--<el-button @click="previewMaterial(material)">-->
                  <!--<el-icon><View /></el-icon>-->
                  <!--{{ $t('materials.preview') }}-->
                <!--</el-button>-->
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="totalMaterials"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog 
      v-model="previewVisible" 
      :title="currentPreviewMaterial?.title"
      width="70%"
      :before-close="closePreview"
    >
      <div v-if="currentPreviewMaterial" class="preview-content">
        <div class="preview-header">
          <!--<img :src="currentPreviewMaterial.cover" :alt="currentPreviewMaterial.title" class="preview-cover" />-->
          <div class="preview-info">
            <h3>{{ currentPreviewMaterial.title }}</h3>
            <p>{{ currentPreviewMaterial.description }}</p>
            <div class="preview-meta">
              <span>分类: {{ currentPreviewMaterial.category }}</span>
              <span>类型: {{ currentPreviewMaterial.type }}</span>
              <!--<span>大小: {{ formatFileSize(currentPreviewMaterial.size) }}</span>-->
            </div>
          </div>
        </div>
        
        <div class="preview-pages">
          <div v-if="currentPreviewMaterial.preview" class="preview-image">
            <img :src="currentPreviewMaterial.preview" alt="预览" />
          </div>
          <div v-else class="preview-placeholder">
            <el-icon :size="60"><Document /></el-icon>
            <p>暂无文档预览</p>
          </div>
        </div>
        
        <div class="preview-actions">
          <el-button type="primary" @click="downloadMaterialFun(currentPreviewMaterial)">
            <el-icon><Download /></el-icon>
            下载材料
          </el-button>
          <el-button @click="closePreview">
            关闭
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Download, 
  View,
  Document,
  Delete,
  Edit,
  Plus
} from '@element-plus/icons-vue'
import { 
  getMaterialsList, 
  getMaterialDetail,
  downloadMaterial
} from '@/api/system'

const { t } = useI18n()
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const imageObj = computed(() => userStore.imageObj)

// 头部轮播图相关
const headerImages = computed(() => {
  const raw = imageObj?.value?.fourUrl
  if (!raw) {
    return ['/src/assets/index/study.png']
  }
  // 支持字符串数组或逗号分隔字符串
  let list = Array.isArray(raw) ? raw : String(raw).split(',')
  list = list.map(s => String(s).trim()).filter(Boolean)
  const resolved = list.map(url => {
    if (/^https?:\/\//i.test(url)) return url
    return (import.meta.env.VITE_BASE_URL || '') + url
  })
  return resolved.length ? resolved : ['/src/assets/index/study.png']
})
const headerImagesKey = computed(() => headerImages.value.join('|'))

// 兼容相对地址
const resolveUrl =(url)=> {
  if (!url) return ''
  if (/^https?:\/\//i.test(url)) return url
  return (import.meta.env.VITE_BASE_URL || '') + url
}

// 头部图片点击事件
const handleHeaderImageClick = (index, url) => {
  // 这里可以根据业务进行跳转或埋点
  // 先占位实现点击事件
  // console.log('clicked header image:', index, url)
}


// 响应式数据
const selectedCategory = ref('all')
const selectedType = ref('all')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const previewVisible = ref(false)
const currentPreviewMaterial = ref(null)
const loading = ref(false)
const totalMaterials = ref(0)
const materials = ref([])

// 获取学习资料列表
const fetchMaterials = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      category: selectedCategory.value !== 'all' ? selectedCategory.value : '',
      type: selectedType.value !== 'all' ? selectedType.value : '',
      keyword: searchKeyword.value
    }
    
    const response = await getMaterialsList(params)
    if (response.code === 200) {
      materials.value = response.rows || []
      totalMaterials.value = response.total || 0
    } else {
      ElMessage.error(response.msg || '获取学习资料列表失败')
    }
  } catch (error) {
    console.error('获取学习资料列表失败:', error)
    ElMessage.error('获取学习资料列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取学习资料详情
const fetchMaterialDetail = async (materialId) => {
  try {
    const response = await getMaterialDetail(materialId)
    if (response.code === 200) {
      return response.data
    } else {
      ElMessage.error(response.msg || '获取学习资料详情失败')
      return null
    }
  } catch (error) {
    console.error('获取学习资料详情失败:', error)
    ElMessage.error('获取学习资料详情失败，请稍后重试')
    return null
  }
}

// 计算属性
const filteredMaterials = computed(() => {
  let filtered = materials.value

  // 按分类筛选
  if (selectedCategory.value !== 'all') {
    filtered = filtered.filter(m => m.category === selectedCategory.value)
  }

  // 按类型筛选
  if (selectedType.value !== 'all') {
    filtered = filtered.filter(m => m.type === selectedType.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(m => 
      m.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      m.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  return filtered
})

// 移除这个计算属性，因为我们现在从API获取总数

// 方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getTagType = (category) => {
  const typeMap = {
    '特定技能': 'primary',
    'JFT': 'success',
    'JLPT': 'warning'
  }
  return typeMap[category] || 'info'
}

const filterMaterials = () => {
  currentPage.value = 1
  fetchMaterials()
}

const previewMaterial = async (material) => {
  try {
    // 获取完整的学习资料详情
    const materialDetail = await fetchMaterialDetail(material.id)
    if (materialDetail) {
      currentPreviewMaterial.value = materialDetail
      previewVisible.value = true
    }
  } catch (error) {
    console.error('获取学习资料详情失败:', error)
  }
}

const closePreview = () => {
  previewVisible.value = false
  currentPreviewMaterial.value = null
}

const downloadMaterialFun = async (material) => {
  try {
    ElMessage.info('开始下载...')
    
    // 调用下载接口
    const response = await downloadMaterial(material.filePath)
    
    // 创建下载链接
    const blob = new Blob([response], { type: 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = material.title + '.pdf'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载完成')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchMaterials()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchMaterials()
}

onMounted(() => {
  // 初始化数据
  fetchMaterials()
})
</script>

<style scoped>
.materials {
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面头部 */
.page-header {
  position: relative;
  height: 300px;
  display: flex;
  align-items: center;
  color: white;
  overflow: hidden;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.el-carousel {
  height: 100%;
}

.header-bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(44, 62, 80, 0.3), rgba(52, 73, 94, 0.3));
}

.header-content {
  position: relative;
  z-index: 2;
  width: 80%;
    margin: auto;
  text-align: center;
}

.header-content h1 {
  font-size: 3rem;
  font-weight: bold;
  margin-bottom: 15px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.header-content p {
  font-size: 1.2rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

/* 筛选器区域 */
.filters-section {
  background: #f8f9fa;
  padding: 30px 0;
  border-bottom: 1px solid #e9ecef;
}

.filters {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 材料区域 */
.materials-section {
  padding: 40px 0;
  background: white;
}

.materials-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
}

.material-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.material-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.material-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.material-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.material-card:hover .material-image img {
  transform: scale(1.05);
}

.material-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.material-card:hover .material-overlay {
  opacity: 1;
}

.material-info {
  padding: 20px;
}

.material-info h3 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin-bottom: 10px;
  line-height: 1.4;
}

.material-description {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.material-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.material-stats {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #999;
}

.material-tags {
  display: flex;
  gap: 5px;
}

.material-actions {
  display: flex;
  gap: 10px;
}

/* 预览对话框 */
.preview-content {
  max-height: 70vh;
  overflow-y: auto;
}

.preview-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.preview-cover {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.preview-info h3 {
  margin-bottom: 10px;
  color: #2c3e50;
}

.preview-info p {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.preview-meta {
  display: flex;
  gap: 20px;
  font-size: 0.9rem;
  color: #999;
}

.preview-pages {
  margin-bottom: 20px;
}

.preview-image img {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  border: 1px solid #e9ecef;
  border-radius: 8px;
}

.preview-placeholder {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  border: 2px dashed #e9ecef;
  border-radius: 8px;
}

.preview-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content h1 {
    font-size: 2rem;
  }
  
  .header-content p {
    font-size: 1rem;
  }
  
  .materials-grid {
    grid-template-columns: 1fr;
  }
  
  .material-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .preview-header {
    flex-direction: column;
  }
  
  .preview-cover {
    width: 100%;
    height: 150px;
  }
}
</style> 